<template>
 <div class="ReleaseGames">
<!--   比赛发布-->
   <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 30px">
     <el-breadcrumb-item :to="{ path: '/backIndex/managementTeam' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>发布资讯</el-breadcrumb-item>
   </el-breadcrumb>
   <div class="table_box">
     <div class="top_title">
       <h1>资讯发布</h1>
     </div>
     <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm ReleaseGames_main">
       <el-form-item label="文章标题" prop="title" style="width: 800px">
         <el-input v-model="ruleForm.title"></el-input>
       </el-form-item>
       <el-form-item label="文章摘要" prop="summary" style="width: 800px">
         <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="ruleForm.summary"></el-input>
       </el-form-item>
       <el-form-item label="文章类型" prop="classification">
         <el-select @change="changeData" v-model="ruleForm.classification" placeholder="请选择">
           <el-option
               v-for="item in options"
               :key="item.value"
               :label="item.label"
               :value="item.value">
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="封面图片" prop="images" class="img" v-show="imgShow">
         <el-upload
             class="avatar-uploader"
             action="/api/v1/upload"
             :headers="headers"
             :data="{dir:'imgs'}"
             :show-file-list="false"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload">
           <img v-if="imagesShow" :src="ruleForm.images" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
       </el-form-item>
       <el-form-item label="文章内容" prop="text">
         <!-- useCustomImaageHandler: 自定义图片上传方式
             image-add：添加图片的一个自动回调-->
         <vue-editor v-model="ruleForm.text" :editor-toolbar="customToolbar" useCustomImaageHandler @image-add="handleImageAdded"></vue-editor>
         <!--       <Editor :text="ruleForm.text"></Editor>-->
       </el-form-item>
       <el-form-item>
         <el-button type="success" @click="submitForm('ruleForm')">立即发布</el-button>
         <el-button @click="resetForm('ruleForm')">重置</el-button>
       </el-form-item>
     </el-form>
   </div>

 </div>
</template>

<script>
import axios from "axios";
import {VueEditor} from "vue2-editor";
// import Editor from "./components/Editor";
export default {
  name: "ReleaseGames",
  components: {
    VueEditor
    // Editor
  },
  data() {
    return {
      customToolbar: [ //自定义工具栏
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
        ["blockquote", "code-block"], // 引用  代码块
        [{ header: 1 }, { header: 2 }], // 1、2 级标题
        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
        [{ script: "sub" }, { script: "super" }], // 上标/下标
        [{ indent: "-1" }, { indent: "+1" }], // 缩进
        [{ size: ["small", false, "large", "huge"] }], // 字体大小
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
        [{ font: [] }], // 字体种类
        [{ align: [] }], // 对齐方式
        ["clean"], // 清除文本格式
        // ["link", "image", "video"] // 链接、图片、视频
        ],
      options: [{
        value: '通知公告',
        label: '通知公告'
      }, {
        value: '赛事动态',
        label: '赛事动态'
      }],
      imgShow: true,//根据文章类型展现图片添加按钮
      imagesShow: false,//上传后的图片展示
      headers: { //图片上传，自定义请求头
        token: window.sessionStorage.getItem('token')
      },
      ruleForm: {
        title: '',
        text: '',
        classification: '',
        images: '',
        summary: '' //
      },
      rules: {
        title: [{ required: true, message: '请输文章标题', trigger: 'blur' },],
        classification: [{ required: true, message: '请输选择文章类型', trigger: 'blur' }],
        text: [{ required: true, message: '请输文章内容', trigger: 'blur' }],
        summary: [{ required: true, message: '请输文章摘要', trigger: 'blur' }],
      }
    };
  },
  methods: {

    changeData(data){
      console.log(data);
      this.imgShow = data !== "通知公告";
    },
    //表单验证
    submitForm(formName) {
      // this.change();
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await this.$api.addArticle(this.ruleForm);
          if(res.success){
            this.resetForm(formName);
            this.imagesShow = false;
            return this.$message.success("成功发布！")
          } else {
            return this.$message.warning("服务器繁忙，请稍后重试！")
          }
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 表单验证

    //封面图片上传
    handleAvatarSuccess(res, file) {
      file === 1;
      // console.log('上传图片的res',res);
      // console.log('返回的URL',this.ruleForm.images);
      if(res.success){
        this.imagesShow = true;
        this.ruleForm.images = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
      }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
      return isJPG;
    },
    //封面图片上传

    //  富文本插入图片
    handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
      formData.append('file', file)

      // console.log("flie:",file);
      let formData = new FormData();
      formData.append("image", file);
      // console.log("formData:",formData);

      axios({
        url: "/api/v1/upload",
        method: "POST",
        data: formData
      })
          .then(result => {
            const url = result.data.url; // Get url from response
            Editor.insertEmbed(cursorLocation, "image", url);
            resetUploader();
          })
          .catch(err => {
            console.log(err);
          });
    }


  },
  mounted() {
  },
}
</script>

<style lang="less" scoped>
.ReleaseGames{
  .table_box{
    .top_title{
      font-size: 25px;
      font-weight: bolder;
      text-align: center;
      margin-bottom: 20px;
    }
    background-color: #ffff;
    padding: 40px;
    box-shadow: 0 2px 7px rgba(187, 172, 172, 0.49), 0 5px 11px rgba(247, 231, 231, 0.36);
    .ReleaseGames_main{
      width: 1020px;
      margin: 0 auto;
      .img{
        .avatar-uploader .el-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          .avatar-uploader-icon {
            border: 1px dashed #d9d9d9;
            font-size: 20px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
          }
          .avatar {
            width: 100px;
            height: 100px;
            margin-right: 20px;
            display: inline-block;
          }
        }
        .avatar-uploader .el-upload:hover {
          border-color: #409EFF;
        }
      }
    }
  }

}



</style>
